package com.ng8866.gateway.config;

import com.ng8866.gateway.balancer.LeastConnectionLoadBalancer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;


@Configuration
@ConditionalOnProperty(prefix = "loadBalancer", name = "enableBalancer", havingValue = "true")
@LoadBalancerClients(defaultConfiguration = {LeastConnectionLoadBalancer.class})
public class LeastConnectionLoadBalancerConfig {

    @Bean
    @ConditionalOnProperty(prefix = "loadBalancer", name = "enableBalancer", havingValue = "true")
    public LeastConnectionLoadBalancer leastConnectionLoadBalancer(Environment environment, LoadBalancerClientFactory clientFactory){
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new LeastConnectionLoadBalancer(clientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class));
    }
}